<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <a-form :model="searchForm" layout="inline" class="search-form">
        <a-form-item label="检验项目编码:">
          <a-input
            v-model="searchForm.itemCode"
            placeholder="请输入"
            style="width: 150px"
          />
        </a-form-item>
        <a-form-item label="检验项目名称:">
          <a-input
            v-model="searchForm.itemName"
            placeholder="请输入"
            style="width: 150px"
          />
        </a-form-item>
        <a-form-item label="指标编码:">
          <a-input
            v-model="searchForm.indexCode"
            placeholder="请输入"
            style="width: 150px"
          />
        </a-form-item>
        <a-form-item label="指标名称:">
          <a-input
            v-model="searchForm.indexName"
            placeholder="请输入"
            style="width: 150px"
          />
        </a-form-item>
        <a-form-item>
          <a-button
            style="margin-right: 10px"
            type="primary"
            @click="handleSearch"
            >查询</a-button
          >
          <a-button @click="handleReset">重置</a-button>
        </a-form-item>
      </a-form>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <a-button type="primary" @click="handleAdd">新增</a-button>
        <a-button
          type="primary"
          status="danger"
          style="margin-left: 10px"
          :disabled="selectedKeys.length === 0"
          @click="handleBatchDelete"
        >
          批量删除
        </a-button>
      </div>
    </div>

    <!-- 表格区域 -->
    <a-table
      v-model:selected-keys="selectedKeys"
      row-key="id"
      :columns="columns"
      :data="tableData"
      :row-selection="rowSelection"
      :pagination="false"
      :bordered="{ cell: true }"
      class="data-table"
    >
      <template #index="{ index }">
        {{ index + 1 }}
      </template>
      <template #operation="{ record }">
        <a-button type="text" status="primary" @click="handleEdit(record)"
          >编辑</a-button
        >
        <a-button type="text" status="danger" @click="handleDelete(record)"
          >删除</a-button
        >
      </template>
    </a-table>

    <!-- 分页区域 -->
    <a-pagination
      class=""
      :total="tableData.length"
      size="medium"
      show-total
      show-jumper
      show-page-size
    />
    <!-- 新增编辑 -->
    <addEdit
      :open-add-edit="openAddEdit"
      :initial-data="itemData"
      @click="addEditClick"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, defineAsyncComponent, watch } from 'vue';
import { Modal } from '@arco-design/web-vue';

const addEdit = defineAsyncComponent(() => import('./addEditPop.vue'));

// 接收父组件传递的患者详情数据和患者ID
const props = defineProps({
  patientDetails: {
    type: Array,
    default: () => [],
  },
  patientId: {
    type: [Number, String],
    default: null,
  },
});

// 搜索表单数据
const searchForm = reactive({
  itemCode: '',
  itemName: '',
  indexCode: '',
  indexName: '',
});

// 原始数据（用于重置功能）
const originalData = ref<any[]>([]);
// 表格数据（用于显示和搜索）
const tableData = ref<any[]>([]);

// 本地存储键名前缀
const STORAGE_KEY_PREFIX = 'patient_details_';

// 从本地存储获取数据
const getDataFromLocalStorage = (patientId: number | string) => {
  try {
    const storedData = localStorage.getItem(
      `${STORAGE_KEY_PREFIX}${patientId}`
    );
    return storedData ? JSON.parse(storedData) : null;
  } catch (e) {
    console.error('从本地存储获取数据失败:', e);
    return null;
  }
};

// 将数据保存到本地存储
const saveDataToLocalStorage = (patientId: number | string, data: any[]) => {
  try {
    localStorage.setItem(
      `${STORAGE_KEY_PREFIX}${patientId}`,
      JSON.stringify(data)
    );
  } catch (e) {
    console.error('保存数据到本地存储失败:', e);
  }
};

// 监听患者详情数据变化
watch(
  [() => props.patientDetails, () => props.patientId],
  ([newVal, newPatientId]) => {
    // 如果没有患者ID，则不进行本地存储操作
    if (!newPatientId) {
      if (newVal && Array.isArray(newVal)) {
        originalData.value = [...newVal];
        tableData.value = [...newVal];
      } else {
        originalData.value = [];
        tableData.value = [];
      }
      return;
    }

    // 检查是否有本地存储的数据
    const storedData = getDataFromLocalStorage(newPatientId);

    if (storedData) {
      // 使用本地存储的数据
      originalData.value = [...storedData];
      tableData.value = [...storedData];
    } else {
      // 使用传入的数据
      if (newVal && Array.isArray(newVal)) {
        // 保存原始数据
        originalData.value = [...newVal];
        // 初始化显示数据
        tableData.value = [...newVal];
        // 保存到本地存储
        saveDataToLocalStorage(newPatientId, newVal);
      } else {
        originalData.value = [];
        tableData.value = [];
      }
    }
  },
  { immediate: true, deep: true }
);

// 表格列配置
const columns = [
  {
    title: '序号',
    dataIndex: 'index',
    render: ({ rowIndex }: { rowIndex: number }) => rowIndex + 1,
    width: 50,
    align: 'center',
  },
  {
    title: '检验项目编码',
    dataIndex: 'itemCode',
    width: 120,
    align: 'center',
  },
  {
    title: '检验项目名称',
    dataIndex: 'itemName',
    width: 150,
    align: 'center',
  },
  {
    title: '指标编码',
    dataIndex: 'indexCode',
    width: 100,
    align: 'center',
  },
  {
    title: '指标名称',
    dataIndex: 'indexName',
    width: 120,
    align: 'center',
  },
  {
    title: '最大值上限预警',
    dataIndex: 'upperLimit',
    width: 140,
    align: 'center',
  },
  {
    title: '最小值下限预警',
    dataIndex: 'lowerLimit',
    width: 140,
    align: 'center',
  },
  {
    title: '操作',
    key: 'operation',
    width: 140,
    align: 'center',
    slotName: 'operation',
  },
];

// 分页相关数据
const currentPage = ref(1);
const pageSize = ref(30);
const total = ref(400);
const jumpPage = ref(1);
const totalPages = ref(Math.ceil(total.value / pageSize.value));
// 控制弹窗显示隐藏
const openAddEdit = ref(false);
const itemData = ref({});

// 选中的行
const selectedKeys = ref<number[]>([]);
const rowSelection = reactive({
  type: 'checkbox',
  showCheckedAll: true,
  onlyCurrent: false,
});

// 搜索功能
const handleSearch = () => {
  const list = originalData.value;
  tableData.value = list
    .filter(
      (data) =>
        !searchForm.indexName ||
        data.indexName
          .toLowerCase()
          .includes(searchForm.indexName.toLowerCase())
    )
    .filter(
      (data) =>
        !searchForm.indexCode ||
        data.indexCode
          .toLowerCase()
          .includes(searchForm.indexCode.toLowerCase())
    )
    .filter(
      (data) =>
        !searchForm.itemName ||
        data.itemName.toLowerCase().includes(searchForm.itemName.toLowerCase())
    )
    .filter(
      (data) =>
        !searchForm.itemCode ||
        data.itemCode.toLowerCase().includes(searchForm.itemCode.toLowerCase())
    );
};

// 重置功能
const handleReset = () => {
  searchForm.itemCode = '';
  searchForm.itemName = '';
  searchForm.indexCode = '';
  searchForm.indexName = '';
  // 重置分页到第一页
  currentPage.value = 1;
  // 清空选中的行
  selectedKeys.value = [];
  // 恢复原始数据
  tableData.value = [...originalData.value];
};

// 新增按钮点击事件
const handleAdd = () => {
  openAddEdit.value = true;
  itemData.value = {};
};
// 编辑功能
const handleEdit = (record: any) => {
  openAddEdit.value = true;
  itemData.value = { ...record };
};

// 删除功能
const handleDelete = (record: any) => {
  // 显示确认弹窗
  Modal.confirm({
    title: '提示',
    content: `是否删除【${record.itemCode}~${record.indexName}】监护指标？`,
    okText: '确定',
    cancelText: '取消',
    onOk: () => {
      // 从原始数据和显示数据中都删除
      originalData.value = originalData.value.filter((item) => item.id !== record.id);
      tableData.value = tableData.value.filter((item) => item.id !== record.id);
      // 保存到本地存储
      if (props.patientId) {
        saveDataToLocalStorage(props.patientId, originalData.value);
      }
    },
  });
};

// 批量删除功能
const handleBatchDelete = () => {
  // 显示确认弹窗
  Modal.confirm({
    title: '提示',
    content: `是否删除所选择数据？`,
    okText: '确定',
    cancelText: '取消',
    onOk: () => {
      // 从原始数据和显示数据中都删除
      originalData.value = originalData.value.filter(
        (item) => !selectedKeys.value.includes(item.id)
      );
      tableData.value = tableData.value.filter(
        (item) => !selectedKeys.value.includes(item.id)
      );
      selectedKeys.value = [];
      // 保存到本地存储
      if (props.patientId) {
        saveDataToLocalStorage(props.patientId, originalData.value);
      }
    },
  });
};
// 根据编码获取检验项目名称
const getInspectionItemName = (code: string) => {
  const map: Record<string, string> = {
    XM001: '血常规',
    XM002: '肝功能',
    XM003: '肾功能',
    XM004: '血脂',
  };
  return map[code] || code;
};

// 根据编码获取检验指标名称
const getInspectionIndexName = (code: string) => {
  const map: Record<string, string> = {
    ZB001: '白细胞',
    ZB002: '红细胞',
    ZB003: '血小板',
    ZB004: '血红蛋白',
  };
  return map[code] || code;
};

// 新增编辑
const addEditClick = ({ type, data }: { type: string; data: any }) => {
  openAddEdit.value = false;
  if (type === 'save') {
    const newRecord = {
      id: data.id || Date.now(), // 如果是编辑则保留原ID，否则生成新ID
      ...data,
      itemName: getInspectionItemName(data.itemCode),
      indexName: getInspectionIndexName(data.indexCode),
    };
    if (!data.id) {
      // 新增
      originalData.value.unshift(newRecord);
      tableData.value.unshift(newRecord);
    } else {
      // 编辑操作
      const originalIndex = originalData.value.findIndex(
        (item) => item.id === data.id
      );
      const displayIndex = tableData.value.findIndex(
        (item) => item.id === data.id
      );
      if (originalIndex !== -1) {
        originalData.value[originalIndex] = newRecord;
      }
      if (displayIndex !== -1) {
        tableData.value[displayIndex] = newRecord;
      }
    }
    // 保存到本地存储
    if (props.patientId) {
      saveDataToLocalStorage(props.patientId, originalData.value);
    }
  }
};
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.search-container {
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: 16px;
}

.action-buttons {
  margin-bottom: 16px;
}

.data-table {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 0;
}

.total-info {
  margin-right: 16px;
  color: var(--color-text-2);
}

.page-size-select {
  margin: 0 16px;
}

:deep(.arco-pagination) {
  justify-content: flex-end;
}
:deep(.arco-table-th) {
  background-color: #dceac6 !important;
  border-bottom-color: #98c059;
  transition: background-color 0.3s ease;
}
</style>